package com.spring.campus_express_delivery.service.serviceImpl;

import com.spring.campus_express_delivery.dao.UsersDao;
import com.spring.campus_express_delivery.entity.PageBean;
import com.spring.campus_express_delivery.entity.Users;
import com.spring.campus_express_delivery.service.UsersService;
import com.spring.campus_express_delivery.util.MyUtil;
import com.spring.campus_express_delivery.util.ResponseEntity;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements UsersService {
    @Resource
    UsersDao usersDao;
    //通过openid来查询此用户是否存在
    @Override
    public Users selectUserByOpenid(String appid){
        return usersDao.selectUserByOpenid(appid);
    }
    //微信小程序注册用户
    @Override
    public void insertWXUser(Users user) {
        usersDao.insertWXUser(user);
    }

   /* @Override
    public Users selectUsersByidentityID_password(String identity_id,String password){
           return usersDao.selectUsersByidentityID_password(identity_id,password);
    }*/
   //根据用户identity_id查询用户信息，web注册用户，登录,根据identity_id查询用户用到
    @Override
    public Users selectUserByIdentityId(String identity_id) {
        return usersDao.selectUserByIdentityId(identity_id);
    }
    //web端注册用户
    @Override
    public void insertWebUser(Users user) {
        usersDao.insertWebUser(user);
    }
    //根据id修改用户信息时需要先查询id
    @Override
    public Users selectUsersById(Integer id){
        return usersDao.selectUsersById(id);
    }
    //根据id修改用户信息
    @Override
    public void updateUsersInfoById(Users users){
         usersDao.updateUsersInfoById(users);
    }
    //修改用户自己的信息
    @Override
    public void  updateInfoByMyself(Users users){
        usersDao.updateInfoByMyself(users);
    }
    //用户列表
    @Override
    public PageBean<Users> selectUsersByPage(int size, int page, String sort, String asc) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        PageBean<Users> pageBean = new PageBean<Users>();
        //封装当前页数
        pageBean.setCurrPage(page);
        //封装页数大小
        pageBean.setPageSize(size);
        //封装排序字段
        pageBean.setPageSort(sort);
        //封装排序规则
        pageBean.setPageAsc(asc);

        //封装总记录数
        int totalCount = usersDao.selectCountByUser();
        pageBean.setTotalCount(totalCount);

        //封装总页数
        double tc = totalCount;
        Double num =Math.ceil(tc/size);//向上取整
        pageBean.setTotalPage(num.intValue());


        map.put("PageStart",(page-1)*size);
        map.put("PageSize", pageBean.getPageSize());
        map.put("PageSort", sort);
        map.put("PageAsc", asc);

        //封装每页显示的数据
        List<Users> lists = usersDao.selectUsersByPage(map);
        pageBean.setLists(lists);
        return pageBean;
    }


    //根据id删除用户
    @Override
    public void  deleteUserById(Integer id){
        usersDao.deleteUserById(id);
    }
    //统计数目
    @Override
    public Map<String, Integer> count(){
        Map<String,Integer> map = new HashMap<>();
        int countByUser=usersDao.selectCountByUser();
        map.put("user",countByUser);
        return map;
    }
    @Override
    public int selectCountByUser() {
        return usersDao.selectCountByUser();
    }
    //Excel导入用户信息
    @Override
    public void importUsersExcel(MultipartFile usersFile) throws IOException {
        Workbook workbook=null;
        String fileName=usersFile.getOriginalFilename();
        if(fileName.endsWith("xls")){
            workbook=new HSSFWorkbook(usersFile.getInputStream());
        }else if(fileName.endsWith("xlsx")){
            workbook=new XSSFWorkbook(usersFile.getInputStream());
        }else{
            throw new IOException("文件不是Excel类型");
        }
        Sheet sheet=workbook.getSheet("sheet1");
        int rows=sheet.getLastRowNum();
        if(rows==0){
            throw new IOException("没有数据导入失败");
        }
        for(int i=1;i<rows+1;i++){
            Row row=sheet.getRow(i);
            if(row!=null){
                Users users=new Users();
                MyUtil myUtil=new MyUtil();
                String identity_id=myUtil.getCellValue(row.getCell(0));
                String password=myUtil.getCellValue(row.getCell(1));
                Integer authority= Integer.parseInt(myUtil.getCellValue(row.getCell(2)));
                String whether_delete="否";
                Users user=usersDao.selectUserByIdentityId(identity_id);
                if(user!=null){
                    ResponseEntity responseEntity;
                    responseEntity=ResponseEntity.forbidden();
                    responseEntity.putDataValue("msg","该用户已存在");
                }else{//keyi
                    users.setIdentity_id(identity_id);
                    users.setPassword(password);
                    users.setAuthority(authority);
                    users.setWhether_delete(whether_delete);
                    usersDao.insertWebUser(users);
                }

            }
        }
    }

    @Override
    public void exportUsersExcel(HttpServletResponse response) throws Exception {

            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("Sheet1");
            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

            HSSFCell cell = row.createCell(0);
            cell.setCellValue("id");//设置他的内容
            cell.setCellStyle(style);//设置样式
            cell = row.createCell(1);//创建第二列
            cell.setCellValue("用户名");//设置他的内容
            cell.setCellStyle(style);//设置样式
            cell = row.createCell(2);//创建第二列
            cell.setCellValue("联系方式");//设置他的内容
            cell.setCellStyle(style);//设置样式
        cell = row.createCell(3);//创建第二列
        cell.setCellValue("地址");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(4);//创建第二列
        cell.setCellValue("备注");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(5);//创建第二列
        cell.setCellValue("权限");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(6);//创建第二列
        cell.setCellValue("密码");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(7);//创建第二列
        cell.setCellValue("头像");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(8);//创建第二列
        cell.setCellValue("唯一标识");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(9);//创建第二列
        cell.setCellValue("授权作用域");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(10);//创建第二列
        cell.setCellValue("请求和回调状态");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(11);//创建第二列
        cell.setCellValue("是否删除");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(12);//创建第二列
        cell.setCellValue("用户学号/工号");//设置他的内容
        cell.setCellStyle(style);//设置样式
        cell = row.createCell(13);//创建第二列
        cell.setCellValue("创建时间");//设置他的内容
        cell.setCellStyle(style);//设置样式

//        cell.setCellValue("分数");
//        cell.setCellStyle(style);


            List<Users> list = usersDao.selectAllUsers();
            for (int i = 0; i < list.size() ; i++) {
                row = sheet.createRow(i + 1);
                Users users = list.get(i);
                row.createCell(0).setCellValue(users.getId());
                row.createCell(1).setCellValue(users.getUsername());
                row.createCell(2).setCellValue(users.getPhone());
                row.createCell(3).setCellValue(users.getAddress());
                row.createCell(4).setCellValue(users.getRemark());
                row.createCell(5).setCellValue(users.getAuthority());
                row.createCell(6).setCellValue("密码不可见");
                row.createCell(7).setCellValue(users.getHead_portrait());
                row.createCell(8).setCellValue(users.getAppid());
                row.createCell(9).setCellValue(users.getScope());
                row.createCell(10).setCellValue(users.getState());
                row.createCell(11).setCellValue(users.getWhether_delete());
                row.createCell(12).setCellValue(users.getIdentity_id());
                row.createCell(13).setCellValue(users.getCreate_time());

//            row.createCell(2).setCellValue(stu.getScore());
//                cell = row.createCell(2);
            }

                OutputStream output = response.getOutputStream();
               // response.reset();
                long filename = System.currentTimeMillis();
                SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
                String fileName = df.format(new Date());
                response.setHeader("Content-disposition", "attachment; filename="+fileName+".xls");
                response.setContentType("application/msexcel");
//                response.reset();
        //https://blog.csdn.net/weixin_41231928/article/details/103313449?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-2.control
//                response.addHeader("Access-Control-Allow-Origin","*");
//                response.addHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE");
//                response.addHeader("Access-Control-Allow-Headers","Content-Type");
                wb.write(output);

    }



    @Override
    public List<Users> selectAllUsers() {
        return usersDao.selectAllUsers();
    }

    @Override
    public Users selectId(int id) {
        return usersDao.selectId(id);
    }


}
